package cn.xfdzx.android.apps.shop.activity;


import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.target.ViewTarget;
import com.bumptech.glide.request.transition.Transition;
import com.luck.picture.lib.tools.ToastUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.login.OneLoginMainActivity;
import cn.xfdzx.android.apps.shop.adapter.XfdShopGoodAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.ConfirmGoodBeen;
import cn.xfdzx.android.apps.shop.bean.HomeSearchXFDGoodBeen;
import cn.xfdzx.android.apps.shop.bean.StoreInfoBeen;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.contract.StoreInfoContract;
import cn.xfdzx.android.apps.shop.presenter.HomeSearchPresenter;
import cn.xfdzx.android.apps.shop.presenter.StoreInfoPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ItemOffsetDecoration;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;
import cn.xfdzx.android.apps.shop.video.VideoActivity;
import cn.xfdzx.android.apps.shop.view.SonicView;

import static android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP;
import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP;
import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;
import static cn.xfdzx.android.apps.shop.apps.Constants.START_CODE;

/**
 * 新发地商铺
 */
public class XFDShopDetailsActivity extends BaseMvpActivity<StoreInfoPresenter> implements StoreInfoContract.View {

    @BindView(R.id.ll_hint)
    LinearLayout llHint;
   @BindView(R.id.ll_state)
    LinearLayout llState;
    @BindView(R.id.view_shop_bg)
    View viewShopBg;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_star)
    TextView tvStar;
    @BindView(R.id.tv_focus_on)
    TextView tvFocusOn;
    @BindView(R.id.iv_shop_logo)
    ImageView ivShopLogo;
    @BindView(R.id.rv_xfd_shop_goods)
    RecyclerView rvXfdShopGoods;
    @BindView(R.id.tv_comprehensive)
    TextView tvComprehensive;
    @BindView(R.id.tv_new_product)
    TextView tvNewProduct;
    @BindView(R.id.tv_sales)
    TextView tvSales;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.view_shop_car_bg)
    View viewShopCarBg;
    @BindView(R.id.tv_total_goods_num)
    TextView tvTotalGoodsNum;//购物车数量
    @BindView(R.id.sonic_view)
    SonicView sonicView;
    @BindView(R.id.rl_video_zhibo)
    RelativeLayout rlVideoZhibo;
    private RelativeLayout.LayoutParams item_bar;

    private TextView public_tv;
    private boolean is_low_price = false;
    private int type = 1;//类别 0-零售 1-批发
    private int page;
    private int limit = Constants.LIMIT;//每页多少条
    private String sid = "";
    private String keyWrod = "";
    private String is_store = "0";
    private String priceOrder = "";
    private String salesOrder = "";
    private String shop_id = "";
    private XfdShopGoodAdapter xfdShopGoodAdapter;
    private int car_num = 0;
    private  int end_postion[] = new int[2];
    private Context mContext;
    private boolean isFocusShop = false;

    private List<HomeSearchXFDGoodBeen.DataBean> mList = new ArrayList<>();
    private String user_curent_lng,user_curent_lat;

    @Override
    public int getLayoutId() {
        return R.layout.activity_xfdshop_details;
    }

    @Override
    public void initView() {
        mContext=XFDShopDetailsActivity.this;
        mPresenter = new StoreInfoPresenter();
        mPresenter.attachView(this);
        shop_id = getIntent().getStringExtra("shop_id");
        user_curent_lng = UtilsData.getPreference(this, "coordinates").getString("coordinates_lng");
        user_curent_lat = UtilsData.getPreference(this, "coordinates").getString("coordinates_lat");
        public_tv = tvComprehensive;
        initHigh();
        StatusBarUtil.setLightStatusBar(this, false, true);
        rvXfdShopGoods.setItemAnimator(new DefaultItemAnimator());
        GridLayoutManager mLayoutManager = new GridLayoutManager(this, 2);
        rvXfdShopGoods.setLayoutManager(mLayoutManager);
        ItemOffsetDecoration itemDecoration = new ItemOffsetDecoration(this, R.dimen.item_offset);
        rvXfdShopGoods.addItemDecoration(itemDecoration);
        rvXfdShopGoods.setNestedScrollingEnabled(false);
        xfdShopGoodAdapter = new XfdShopGoodAdapter(this, mList,mPresenter,end_postion);
        xfdShopGoodAdapter.setOnItemClickListener(new ItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (EmptyUtil.isEmpty(APP_TOKEN)){
                    Intent intent = new Intent(XFDShopDetailsActivity.this, OneLoginMainActivity.class);
                    startActivity(intent);
                    return;
                }

                Intent intent = new Intent(XFDShopDetailsActivity.this, XFDGoodsDeatailsActivity.class);
                intent.putExtra("good_id", mList.get(position).getId() + "");
                startActivity(intent);
            }
        });
        rvXfdShopGoods.setAdapter(xfdShopGoodAdapter);

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

                page = 1;
                mPresenter.initList(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, shop_id, keyWrod, priceOrder, salesOrder, "");
            }
        });
        car_num = UtilsData.getPreference(this, "carCount").getInteger("car_pf_count");
        if (car_num == 0) {
            viewShopCarBg.setBackgroundResource(R.drawable.round_hui_bg);
            tvTotalGoodsNum.setVisibility(View.GONE);
        } else {
            tvTotalGoodsNum.setVisibility(View.VISIBLE);
            viewShopCarBg.setBackgroundResource(R.drawable.round_green_bg);
        }
        tvTotalGoodsNum.setText(car_num + "");


        page = 1;
        priceOrder = "";
        salesOrder = "";
        mPresenter.initData(getIntent().getStringExtra("shop_id"), "1");
        mPresenter.initList(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, shop_id, keyWrod, priceOrder, salesOrder, "");

        initOnPreDrawListener();
    }
    private void initOnPreDrawListener() {
        final ViewTreeObserver viewTreeObserver = this.getWindow().getDecorView().getViewTreeObserver();
        viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                tvTotalGoodsNum.getLocationInWindow(end_postion);
                // 移除OnPreDrawListener事件监听
                getWindow().getDecorView().getViewTreeObserver().removeOnPreDrawListener(this);

                return true;
            }
        });
    }
    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);
    }

    @Override
    public void showLoading() {
        ProgressDialog.getInstance().show(this);
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @OnClick({R.id.rl_shop_car, R.id.iv_back, R.id.tv_comprehensive, R.id.tv_new_product,
            R.id.tv_sales, R.id.tv_price, R.id.view_shop_details,
            R.id.rl_search_shop_goods,R.id.tv_focus_on})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.rl_shop_car:
                if (Utils.isFastClick()) {
                    if (EmptyUtil.isEmpty(APP_TOKEN)) {
                        Intent intent = new Intent(XFDShopDetailsActivity.this, OneLoginMainActivity.class);
                        startActivity(intent);
                        return;
                    }
                    //购物车 跳转
                    Intent intent = new Intent(this, GoodCarActivity.class);
                    intent.putExtra("type", 1);
                    startActivity(intent);
                }
                break;
            case R.id.tv_comprehensive:

                text_select(1);
                public_tv = tvComprehensive;
                break;
            case R.id.tv_new_product:

                text_select(2);
                public_tv = tvNewProduct;
                break;
            case R.id.tv_sales:

                text_select(3);
                public_tv = tvSales;
                break;
            case R.id.tv_price:

                text_select(4);
                public_tv = tvPrice;
                break;
            case R.id.view_shop_details:
//                if (Utils.isFastClick()){
//                intent = new Intent(this, XFDShopIntroduceActivity.class);
//                startActivity(intent);}
                break;
            case R.id.rl_search_shop_goods:
                if (Utils.isFastClick()){
                intent = new Intent(this, SearchDefultActivity.class);
                startActivityForResult(intent, START_CODE);}
                break;
            case R.id.tv_focus_on://关注店铺
                if (EmptyUtil.isNotEmpty(APP_TOKEN)){
                    if (Utils.isFastClick()){
                        mPresenter.getFocusShop(shop_id);
                    }
                }else {
                    Intent intent = new Intent(this,OneLoginMainActivity.class);
                    startActivity(intent);
                }
                break;
        }
    }

    Intent intent;

    private void text_select(int position) {
        if (position == 4) {
            if (is_low_price) {
                is_low_price = false;
            } else {
                is_low_price = true;
            }
        } else {

            is_low_price = false;
        }
        public_tv.setTextColor(getResources().getColor(R.color.color_393939));
        switch (position) {
            case 1:
                Drawable nav_up1 = getResources().getDrawable(R.drawable.icon_xfd_price);
                nav_up1.setBounds(0, 0, nav_up1.getMinimumWidth(), nav_up1.getMinimumHeight());
                tvPrice.setCompoundDrawables(null, null, nav_up1, null);
                tvComprehensive.setTextColor(getResources().getColor(R.color.color_02C557));
                page = 1;
                priceOrder = "";
                salesOrder = "";
                mPresenter.initList(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, shop_id, keyWrod, priceOrder, salesOrder, "");
                break;
            case 2:
                Drawable nav_up2 = getResources().getDrawable(R.drawable.icon_xfd_price);
                nav_up2.setBounds(0, 0, nav_up2.getMinimumWidth(), nav_up2.getMinimumHeight());
                tvPrice.setCompoundDrawables(null, null, nav_up2, null);
                tvNewProduct.setTextColor(getResources().getColor(R.color.color_02C557));
                Toast.makeText(this, "新品功能暂未开放", Toast.LENGTH_SHORT).show();
                break;
            case 3:
                tvSales.setTextColor(getResources().getColor(R.color.color_02C557));
                Drawable nav_up3 = getResources().getDrawable(R.drawable.icon_xfd_price);
                nav_up3.setBounds(0, 0, nav_up3.getMinimumWidth(), nav_up3.getMinimumHeight());
                tvPrice.setCompoundDrawables(null, null, nav_up3, null);
                page = 1;
                priceOrder = "";
                salesOrder = "desc";
                mPresenter.initList(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, shop_id, keyWrod, priceOrder, salesOrder, "");
                break;
            case 4:
                if (is_low_price) {
                    Drawable nav_up = getResources().getDrawable(R.drawable.icon_xfd_price_low);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                    tvPrice.setCompoundDrawables(null, null, nav_up, null);
                    page = 1;
                    priceOrder = "asc";
                    salesOrder = "";
                    mPresenter.initList(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, shop_id, keyWrod, priceOrder, salesOrder, "");
                } else {
                    Drawable nav_up = getResources().getDrawable(R.drawable.icon_xfd_price_high);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                    tvPrice.setCompoundDrawables(null, null, nav_up, null);
                    page = 1;
                    priceOrder = "desc";
                    salesOrder = "";
                    mPresenter.initList(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, shop_id, keyWrod, priceOrder, salesOrder, "");
                }
                tvPrice.setTextColor(getResources().getColor(R.color.color_02C557));
                break;
        }

    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    protected void onStop() {
        super.onStop();
        if (null!=sonicView) {
            sonicView.stop();
        }
    }

    @Override
    public void onInitSuccess(StoreInfoBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            //直播的状态
            if (bean.getData().getLive_id()==0){
                rlVideoZhibo.setVisibility(View.GONE);
            }else {
                rlVideoZhibo.setVisibility(View.VISIBLE);
                rlVideoZhibo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(mContext, VideoActivity.class);
                        intent.putExtra("live_id", bean.getData().getLive_id() + "");
                        intent.putExtra("shop_type", "1");
                         startActivity(intent);
                    }
                });
            }

            RoundedCorners roundedCorners = new RoundedCorners(20);
            //通过RequestOptions扩展功能,override:采样率,因为ImageView就这么大,可以压缩图片,降低内存消耗
            RequestOptions options = RequestOptions.bitmapTransform(roundedCorners).override(200, 200);
            options.placeholder(R.drawable.icon_defult)//图片加载出来前，显示的图片
                    .fallback(R.drawable.icon_defult) //url为空的时候,显示的图片
                    .error(R.drawable.icon_defult);
            Glide.with(this).load(bean.getData().getLogo()).apply(options.transform(new CenterCrop(), roundedCorners)).into(ivShopLogo);
            Glide.with(this).load(bean.getData().getLogo()).listener(new RequestListener<Drawable>() {
                @Override
                public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                    //失败加载的默认图片
//                    viewShopBg.setBackground(getResources().getDrawable(R.drawable.image_shop_xfd));
                    return false;
                }

                @Override
                public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                    //成功加载的图片
                    viewShopBg.post(() -> {
                        viewShopBg.setBackground(resource);
                    });
                    return true;
                }
            }).into(viewShopBg.getWidth(), viewShopBg.getHeight());
            tvShopName.setText(bean.getData().getName());
            tvStar.setText(bean.getData().getStar() + "分");
            isFocusShop = bean.getData().isIs_collect();
            if (isFocusShop){
                tvFocusOn.setText("已关注");
            }else {
                tvFocusOn.setText("关注");
            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onListSuccess(HomeSearchXFDGoodBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (page == 1) {
                mList.clear();
                mRefreshLayout.setNoMoreData(false);
                mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                        mPresenter.initList(false, false,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, shop_id, keyWrod, priceOrder, salesOrder, "");
                    }
                });
            }
            if (bean.getData().size() == 0) {
//                if (page==1){
//                    tvCantFind.setVisibility(View.VISIBLE);
//                }
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                page++;
                mList.addAll(bean.getData());
                xfdShopGoodAdapter.notifyDataSetChanged();
            }
            if (mList.size()==0){
                llHint.setVisibility(View.VISIBLE);
            }else {
                llHint.setVisibility(View.GONE);
            }
        } else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onAddCarSuccess(ConfirmGoodBeen bean,int position,int total_num) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (tvTotalGoodsNum.getVisibility() != View.VISIBLE) {
                tvTotalGoodsNum.setVisibility(View.VISIBLE);
                viewShopCarBg.setBackgroundResource(R.drawable.round_green_bg);
            }
            mList.get(position).setAdd_cart_num(total_num);
            xfdShopGoodAdapter.notifyDataSetChanged();
            UtilsData.getPreference(this, "carCount").put("car_pf_count",bean.getData().getCount().getPfcount());
            tvTotalGoodsNum.setText(bean.getData().getCount().getPfcount() + "");
            Toast.makeText(this, "加入购物车成功", Toast.LENGTH_SHORT).show();

        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(this, "login").remove("head_url");
                UtilsData.getPreference(this, "login").remove("nickname");
                UtilsData.getPreference(this, "login").remove("is_store");
                UtilsData.getPreference(this, "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(this, OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getFocusShopSuccess(StoreInfoBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            isFocusShop = !isFocusShop;
            if (isFocusShop){
                tvFocusOn.setText("已关注");
            }else {
                tvFocusOn.setText("关注");
            }
        }else {
            ToastUtils.s(this,bean.getMsg());
        }
    }

    @Override
    public void finishRefresh() {
        mRefreshLayout.finishRefresh(true);//刷新完成
    }

    @Override
    public void finishLoadMore() {
        mRefreshLayout.finishLoadMore(true);//加载完成
    }


    @Override
    protected boolean isUseFullScreenMode() {
        return true;
    }

    @Override
    protected void onDestroy() {
        mList.clear();
        mList = null;
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == START_CODE) {
            if (resultCode == RESULT_OK) {
                keyWrod = data.getStringExtra("key");
                tvSearch.setText(keyWrod);
                page = 1;
                mPresenter.initList(true, true,user_curent_lng,user_curent_lat, sid, page + "", limit + "", type + "", is_store, shop_id, keyWrod, priceOrder, salesOrder, "");
            }
        }

    }
}
